package cn.rkylin.oms.system.logistics.controller;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;

import cn.rkylin.core.controller.ApolloController;
import cn.rkylin.oms.common.annotation.SystemControllerLog;
import cn.rkylin.oms.common.consts.YesNoConst;
import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;
import cn.rkylin.oms.system.logistics.dao.LogisticsDAOImpl;
import cn.rkylin.oms.system.logistics.domain.Logistics;
import cn.rkylin.oms.system.logistics.service.ILogisticsService;
import cn.rkylin.oms.system.logistics.vo.LogisticsVO;

/**
 * 物流公司管理层
 */
@Controller
@RequestMapping("/lgst")
public class LogisticsController extends ApolloController {

    private static final Log logger = LogFactory.getLog(LogisticsController.class);

    // 常量定义
    private static final String PAGE_SELECT_STATEMENT = "pageSelectShop"; // 分页语句Statement名称
    private static final String GOTO_LGST_LIST = "/system/organization/logistics/LogisticsList"; // 跳转到店铺列表页

    /**
     * 物流公司务层
     */
    @Autowired
    private ILogisticsService logisticsService;

    /**
     * 构造函数
     */
    public LogisticsController() {

    }

    /**
     * 跳转到物流公司列表
     */
    @RequestMapping(value = "/gotoLogisticsList")
    public String gotoLogisticsList() {
        return GOTO_LGST_LIST;
    }

    @ResponseBody
    @RequestMapping(value = "/getLgstByProjectId", method = RequestMethod.GET)
    public Map<String, Object> getLgstByProjectId(String projectId) throws Exception {
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            // 用于返回值的json对象
            Map<String, Object> resultMap = new HashMap<String, Object>();
            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            if (currentUser == null) {
                resultMap.put(JSON_RESULT, FAILED);
                resultMap.put(JSON_MSG, "当前用户失效");
                return resultMap;
            }
            // 前台搜索条件，此处只有一个角色名称
            LogisticsVO param = new LogisticsVO();
            param.setPrjId(projectId);
            // 获取分页数据
            PageInfo<LogisticsVO> lgstVOList = logisticsService.findByWhere(0, Integer.MAX_VALUE, param);
            // 设置返回结果内容
            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(RECORDS_FILTERED, lgstVOList.getTotal());
            returnMap.put(RECORDS_TOTAL, lgstVOList.getTotal());
            returnMap.put(RETURN_DATA, lgstVOList.getList());
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        // 生成返回结果json串，null内容也需要返回
        return returnMap;
    }

    /**
     * 方法简要描述信息.
     * <p>
     * 描述: 根据查询条件获取物流公司信息
     * </p>
     * <p>
     * 备注: 详见顺序图<br>
     * </p>
     *
     * @param quickSearch
     * @param start
     * @param length
     */
    @ResponseBody
    @RequestMapping(value = "/LgstList", method = RequestMethod.GET)
    public Map<String, Object> getLgstList(String quickSearch, @RequestParam(required = false, defaultValue = "0") int start,
            @RequestParam(required = false, defaultValue = "10") int length) throws Exception {
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            // 前台搜索条件，此处只有一个角色名称
            LogisticsVO param = new LogisticsVO();
            // 设置项目Id
            CurrentUser currUser = WebContextFactory.getWebContext().getCurrentUser();
            param.setPrjId(currUser.getCurrentProject().getPrjId());
            if (quickSearch != null) {
                quickSearch = URLDecoder.decode(quickSearch, "UTF-8");
                if (StringUtils.isNotEmpty(quickSearch)) {
                    param.setSearchCondition(quickSearch);
                }
            }
            // 处理分页
            if (length == -1) {
                length = Integer.MAX_VALUE;
            }
            int page = start / length + 1;
            // 处理转义的字段
            Map<String, String> replaceFieldsMap = new HashMap<String, String>();
            replaceFieldsMap.put("validateStatus", "validate");
            replaceFieldsMap.put("status", "enable");
            // 排序语句生成
            String orderStatement = getOrderString(LogisticsDAOImpl.class.getName(), PAGE_SELECT_STATEMENT, replaceFieldsMap);
            if (StringUtils.isNotEmpty(orderStatement)) {
                param.setOrderBy(orderStatement);
            }
            // 获取分页数据
            PageInfo<LogisticsVO> lgstVOList = logisticsService.findByWhere(page, length, param);
            // 设置返回结果内容
            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(RECORDS_FILTERED, lgstVOList.getTotal());
            returnMap.put(RECORDS_TOTAL, lgstVOList.getTotal());
            returnMap.put(RETURN_DATA, lgstVOList.getList());

        } catch (Exception ex) {
            logger.error(ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        // 生成返回结果json串，null内容也需要返回
        return returnMap;
    }

    /**
     * 删除物流公司
     *
     * @param lgstIds
     */
    @ResponseBody
    @RequestMapping(value = "/deleteLgst")
    @SystemControllerLog(module = "物流公司", operation = "删除物流公司", keyCode = "lgstIds")
    public Map<String, Object> deleteLgst(String lgstIds) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            if (lgstIds.substring(0, 1).equals(",")) {
                lgstIds = lgstIds.substring(1);
            }
            if (lgstIds.substring(lgstIds.length() - 1, lgstIds.length()).equals(",")) {
                lgstIds = lgstIds.substring(lgstIds.length() - 1);
            }
            logisticsService.delete(lgstIds);
            returnMap.put(JSON_RESULT, SUCCESS);
        } catch (Exception ex) {
            logger.error(ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        returnMap.put("lgstIds", lgstIds);
        return returnMap;
    }

    /**
     * 添加物流公司
     *
     * @param lgstVO
     */
    @ResponseBody
    @RequestMapping(value = "/addLgst")
    @SystemControllerLog(module = "物流公司", operation = "添加物流公司", keyCode = "lgstId")
    public Map<String, Object> addLgst(@RequestBody LogisticsVO lgstVO) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            CurrentUser currUser = WebContextFactory.getWebContext().getCurrentUser();
            lgstVO.setPrjId(currUser.getCurrentProject().getPrjId()); // 项目Id

            List<LogisticsVO> lgstVOCheckResult = null;
            // check code
            if (StringUtils.isNotBlank(lgstVO.getLgstCode())) {
                LogisticsVO lgstCheckCode = new LogisticsVO();
                lgstCheckCode.setLgstCode(lgstVO.getLgstCode());
                lgstCheckCode.setPrjId(currUser.getCurrentProject().getPrjId());
                lgstVOCheckResult = logisticsService.getLgstByCondition(lgstCheckCode);
                if (lgstVOCheckResult.size() >= 1) {
                    returnMap.put(JSON_RESULT, FAILED);
                    returnMap.put(JSON_MSG, "该物流公司编码已存在");
                    return returnMap;
                }
            } else {
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, "物流公司编码为空");
                return returnMap;
            }

            // check name
            if (StringUtils.isNotBlank(lgstVO.getLgstName())) {
                LogisticsVO lgstCheckName = new LogisticsVO();
                lgstCheckName.setLgstName(lgstVO.getLgstName());
                lgstCheckName.setPrjId(currUser.getCurrentProject().getPrjId());
                lgstVOCheckResult = logisticsService.getLgstByCondition(lgstCheckName);
                if (lgstVOCheckResult.size() >= 1) {
                    returnMap.put(JSON_RESULT, FAILED);
                    returnMap.put(JSON_MSG, "该物流公司名称已存在");
                    return returnMap;
                }
            } else {
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, "物流公司名称为空");
                return returnMap;
            }
            lgstVO.setDeleted("n");
            lgstVO.setLgstId(java.util.UUID.randomUUID().toString().replaceAll("-", ""));

            lgstVO.setEntId(currUser.getCurrentProject().getEntId());

            // TODO 这里是走MDM系统，同步过去，获得主键，然后等着此主数据被审批
            lgstVO.setLgstMcode("");

            logisticsService.insert(lgstVO);
            returnMap.put(JSON_RESULT, SUCCESS);
        } catch (Exception ex) {

            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
            System.out.println(ex);
            System.out.println(returnMap);
        }
        returnMap.put("lgstId", lgstVO.getLgstId());
        return returnMap;
    }

    /**
     * 修改物流公司
     *
     * @param lgstVO
     */
    @ResponseBody
    @RequestMapping(value = "/updateLgst")
    @SystemControllerLog(module = "物流公司", operation = "修改物流公司", keyCode = "lgstId")
    public Map<String, Object> updateLgst(@RequestBody LogisticsVO lgstVO) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        CurrentUser currUser = WebContextFactory.getWebContext().getCurrentUser();
        lgstVO.setPrjId(currUser.getCurrentProject().getPrjId()); // 项目Id
        try {
            String updateLgstName = lgstVO.getLgstName();
            String lgstName = lgstVO.getUpdateLgstName();
            if (!updateLgstName.equals(lgstName)) {
                LogisticsVO lgstVO2 = new LogisticsVO();
                lgstVO2.setPrjId(lgstVO.getPrjId());
                lgstVO2.setLgstName(updateLgstName);
                List<LogisticsVO> storVOList = logisticsService.getLgstByCondition(lgstVO2);
                if (storVOList.size() >= 1) {
                    returnMap.put(JSON_RESULT, FAILED);
                    returnMap.put(JSON_MSG, "该物流公司名称已存在");
                    return returnMap;
                }
            }
            String updateLgstCode = lgstVO.getLgstCode();
            String lgstCode = lgstVO.getUpdateLgstCode();
            if (!updateLgstCode.equals(lgstCode)) {
                LogisticsVO lgstVO3 = new LogisticsVO();
                lgstVO3.setPrjId(lgstVO.getPrjId());
                lgstVO3.setLgstCode(updateLgstCode);
                List<LogisticsVO> lgstVOList2 = logisticsService.getLgstByCondition(lgstVO3);
                if (lgstVOList2.size() >= 1) {
                    returnMap.put(JSON_RESULT, FAILED);
                    returnMap.put(JSON_MSG, "该物流公司编码已存在");
                    return returnMap;
                }
            }
            // 处理缺省物流公司
            if (lgstVO.getIsDefault().equalsIgnoreCase("y") && StringUtils.isNotBlank(lgstVO.getPrjId())) {
                LogisticsVO updateDefault = new LogisticsVO();
                updateDefault.setIsDefault(YesNoConst.NO);
                updateDefault.setPrjId(lgstVO.getPrjId());
                logisticsService.update(updateDefault);
            }

            // 保存物流公司
            logisticsService.update(lgstVO);
            returnMap.put(JSON_RESULT, SUCCESS);
        } catch (Exception ex) {
            logger.error(ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        returnMap.put("lgstId", lgstVO.getLgstId());
        return returnMap;
    }

    /**
     * 获取物流公司详细
     *
     * @param lgstId
     */
    @ResponseBody
    @RequestMapping(value = "/getLgstDetail", method = RequestMethod.POST)
    public Map<String, Object> getStorDetail(String lgstId) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            Logistics lgstDetail = logisticsService.selectLgstDetail(lgstId);
            returnMap.put("lgstDetail", lgstDetail);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnMap;
    }

    /**
     * 获取项目下默认物流公司
     *
     * @param prjId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = { "/getDefaultLgst" })
    public Map<String, Object> getDefaultLgst(String prjId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            Logistics lgst = logisticsService.getDefaultLgst(prjId);
            if (lgst != null) {
                returnMap.put(JSON_RESULT, SUCCESS);
                returnMap.put("lgstId", lgst.getLgstId());// 物流公司Id
                returnMap.put("lgstName", lgst.getLgstName());// 物流公司名称
                returnMap.put("lgstCode", lgst.getLgstCode());// 物流公司编码
            } else {
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, "获取项目下默认物流公司失败");
            }

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        return returnMap;
    }

}
